package com.unisound.tracelog.common.annotation.log;

import com.unisound.tracelog.common.utils.CommonUtils;
import com.unisound.tracelog.common.utils.JsonUtils;
import com.unisound.tracelog.common.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(Log)")
    public void logPointcut() {
    }

    @Around("logPointcut()")
    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        String name = logAnnotation.value();
        if (StringUtils.isEmpty(name)) name = method.getName();

        String traceId = UUIDUtils.simpleUuid();

        String request = JsonUtils.toJson(CommonUtils.argsMap(joinPoint.getArgs()));
        LOGGER.info("[{}]【{}】 start. 请求:{}", traceId, name, request);
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        LOGGER.info("[{}]【{}】 end. 耗时{}ms 请求:{} 响应:{}", traceId, name, endTime - startTime, request, JsonUtils.toJson(result));
        return result;
    }

}
